<template>
  <div class="group">
    <!-- 操控区 -->
    <div class="handler-box">
      <div class="leftWrap">
        <h1>分组名称</h1>
        <el-input placeholder="请输入分组名称" size="small" v-model="input" clearable></el-input>
        <h2>我的分组</h2>
        <el-switch v-model="value" active-color="#409EFF" inactive-color="#DCDFE6"></el-switch>
        <el-button type="primary" icon="el-icon-search" size="small" @click="listSearch">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="reset">重置</el-button>
      </div>
      <el-button type="primary" plain icon="el-icon-plus" size="small" @click="visible = true">新增</el-button>
    </div>
    <!-- 表格区 -->
    <el-table stripe border :data="tableData" v-loading="tableLoading">
      <el-table-column label="分组名称" align="center" prop="groupName" min-width="15%"></el-table-column>
      <el-table-column label="分组排序" align="center" prop="groupOrder" min-width="10%"></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="formatterTime"
        min-width="15%"
      ></el-table-column>
      <el-table-column label="备注" prop="remark" min-width="35%"></el-table-column>
      <el-table-column label="操作" align="center" min-width="25%">
        <template v-slot="{ row }">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            style="padding: 7px 4px; background-color: #ffba00;border:transparent;width:auto"
          >查看设备</el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            style="padding: 7px 4px; background-color: #13ce66;border:transparent;width:auto"
            @click="OptionUpdate(row)"
          >添加设备</el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            style="padding: 7px 4px; background-color:  #1890ff;border:transparent;width:auto"
            @click="triggerUpdate(row)"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <el-pagination
      background
      layout="total,sizes, prev, pager, next, jumper"
      :page-size.sync="pagination.pageSize"
      :total="pagination.total"
      :current-page.sync="pagination.pageNum"
      @current-change="init"
      @size-change="init"
    ></el-pagination>

    <!-- dialog区 新增/修改  -->
    <el-dialog
      width="30%"
      :title="+ruleForm.groupId === 0 ? `添加设备分组` : `修改设备分组`"
      :visible="visible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closeDialog"
    >
      <el-form label-width="100px" :model="ruleForm" :rules="rules" ref="formIns">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="ruleForm.groupName"></el-input>
        </el-form-item>
        <el-form-item label="分组排序" prop="groupOrder">
          <el-input v-model="ruleForm.groupOrder"></el-input>
        </el-form-item>
        <el-form-item label="备注"  prop="remark">
          <el-input type="textarea" v-model="ruleForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="confirmLoading" @click="submit">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </template>
    </el-dialog>

    <!-- dialog区 添加设备 -->
    <el-dialog
      width="45%"
      title="选择设备"
      :visible="visibleAdd"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closeDialogAdd"
    >
      <!-- 搜索栏 -->
      <div class="topWrap">
        <h1>设备名称</h1>
        <el-input placeholder="请输入设备名称" v-model="deviceName" size="small" clearable></el-input>
        <el-button type="primary" icon="el-icon-search" size="small" @click="listSearchAdd">搜索</el-button>
      </div>

      <!-- 表格 -->
      <el-table stripe border 
      size="small"
      :data="tableDataAdd" 
      v-loading="tableLoadingAdd">
        <el-table-column
          type="selection"
          min-width="4%"
          align="center"
        ></el-table-column>
        <el-table-column label="设备名称" align="center" prop="deviceName" min-width="20%"></el-table-column>
        <el-table-column label="设备编号" align="center" prop="serialNumber" min-width="20%"></el-table-column>
        <el-table-column label="产品名称" align="center" prop="productName" min-width="18%"></el-table-column>
        <el-table-column label="设备类型" align="center" prop="isOwner" min-width="15%">
          <template v-slot="{ row }">
            <el-tag :type="row.isOwner===1?'':'info'">{{row.isOwner===1?'拥有':'不拥有'}}</el-tag>
          </template>
          <el-tag>标签一</el-tag>
        </el-table-column>
        <el-table-column label="设备状态" align="center" prop="firmwareVersion" min-width="23%">
          <template v-slot="{ row }">
            <el-tag :type="row.firmwareVersion===1?'warning':'info'">{{row.firmwareVersion===1?'未激活':'离线'}}</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        background
        layout="total,sizes, prev, pager, next, jumper"
        :page-size.sync="paginationAdd.pageSize"
        :total="paginationAdd.total"
        :current-page.sync="paginationAdd.pageNum"
        @current-change="initAdd"
        @size-change="initAdd"
      ></el-pagination>
    
      <template #footer>
        <el-button type="primary" @click="closeDialogAdd">确定</el-button>
        <el-button @click="closeDialogAdd">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Group",
  data() {
    // 校验排序值
    const checkGroupOrder = (_, value, callback) => {
      if (value.length === 0) {
        callback(new Error("分组排序不能为空"));
        return;
      }
      let reg = /^(\d|([1-9]\d+))$/;
      if (!reg.test(value)) {
        callback(new Error("排序值必须为数字"));
        return;
      }
      if (reg.test(value) && value <= 99) {
        callback();
        return;
      }
      callback(new Error("排序最大值为99"));
    };
    return {
      input: "",
      value: false,
      // 表格相关
      tableData: [],
      tableLoading: false,
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 表单相关
      visible: false,
      confirmLoading: false,
      ruleForm: {
        createBy: '',
        createTime:'',
        delFlag: '',
        groupId: 0, //分组id
        groupName: '', //分组名称
        groupOrder: '', //分组排序
        remark: '', //备注
        updateBy: '',
        updateTime: '',
        userId: '',
        userName:''
      },
      rules: {
        groupName: [
          { required: true, message: "分组名称不能为空", trigger: "blur" }
        ],
        groupOrder: [
          { required: true, validator: checkGroupOrder, trigger: "blur" }
        ],
        remark: [
          { required: true, message: "备注不能为空", trigger: "blur" }
        ],
      },
      // 选择设备
      visibleAdd:false,
      tableLoadingAdd: false,
      deviceName: '',//搜索功能
      tableDataAdd: [],
      userId:1,
      paginationAdd: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
    };
  },
  methods: {
    // 根据当前页&每页展示条数，从服务器获取列表数据
    async init() {
      this.tableLoading = true;
      try {
        let { pageNum, pageSize } = this.pagination;
        let { code, rows, total } = await this.$http.group.list(
          pageNum,
          pageSize
        );
        if (code === 200) {
          // console.log(rows);
          this.pagination.total = total;
          this.tableData = rows;
        } else {
          this.pagination.total = 0;
          this.tableData = [];
        }
      } catch (_) {
        _;
      }
      this.tableLoading = false;
    },
    // 搜索功能
    async listSearch(){
      try {
        let { pageNum, pageSize } = this.pagination;
        let inputValue=this.input;
        let { code, rows, total } = await this.$http.group.listSearch(
          pageNum,
          pageSize,
          inputValue
        );
        if (code === 200) {
          // console.log(rows);
          this.pagination.total = total;
          this.tableData = rows;
        } else {
          this.pagination.total = 0;
          this.tableData = [];
        }
      } catch (_) {
        _;
      }
    },
    // 弹框搜索功能
    async listSearchAdd(){
      try {
        let { pageNum, pageSize } = this.paginationAdd;
        let deviceName=this.deviceName;
        let userId=this.userId;
        let { code, rows, total } = await this.$http.group.listByGroupSearch(
          pageNum,
          pageSize,
          userId,
          deviceName
        );
        if (code === 200) {
          // console.log(rows);
          this.paginationAdd.total = total;
          this.tableDataAdd = rows;
        } else {
          this.paginationAdd.total = 0;
          this.tableDataAdd = [];
        }
      } catch (_) {
        _;
      }
    },
    // 表格日期格式化
    formatterTime(row) {
      let str = row.createTime;
      let pre = str.split(" ")[0];
      return pre;
    },
    // 关闭弹框 & 清空表单信息
    closeDialog() {
      this.visible = false;
      this.confirmLoading = false;
      this.ruleForm = {
        createBy: '',
        createTime:'',
        delFlag: '',
        groupId: 0, //分组id
        groupName: '', //分组名称
        groupOrder: '', //分组排序
        remark: '', //备注
        updateBy: '',
        updateTime: '',
        userId: '',
        userName:''
      };
    },
    // 重置按钮
    reset(){
      this.pagination.pageNum=1;
      this.pagination.pageSize=10;
      this.init();
    },
    // 提交按钮：新增/修改信息
    async submit() {
      try {
        await this.$refs.formIns.validate();
        // 向服务器发送请求
        this.confirmLoading = true;
        let {createBy,createTime,delFlag,groupId,groupName,groupOrder,remark,updateBy,updateTime,userId,userName} = this.ruleForm;
        let funcAPI = this.$http.group.groupAdd; //新增
        let data = {
          createBy,
          createTime,
          delFlag,
          groupId, //分组id
          groupName, //分组名称
          groupOrder, //分组排序
          remark, //备注
          updateBy,
          updateTime,
          userId,
          userName
        };
        if (+groupId !== 0) {
          // 修改
          funcAPI = this.$http.group.groupUpdate;
        }
        let { code } = await funcAPI(data);
        if (+code === 200) {
          this.$message.success("恭喜您，操作成功！");
          this.closeDialog();
          this.init();
        } else {
          this.$message.error("操作失败，请稍后再试！");
        }
      } catch (_) {}
      this.confirmLoading = false;
    },
    // 触发修改操作
    async triggerUpdate(row) {
      // console.log(row);
      let { createBy,createTime,delFlag,groupId,groupName,groupOrder,remark,updateBy,updateTime,userId,userName } = row;
      // 先把修改项的ID存储到表单状态中
      this.ruleForm.groupId = groupId;
      // 把信息填充到各个表单中{row中包含表单需要的数据，直接赋值即可}
      this.ruleForm.createBy = createBy;
      this.ruleForm.createTime = createTime;
      this.ruleForm.delFlag = delFlag;
      this.ruleForm.groupName = groupName;
      this.ruleForm.groupOrder = groupOrder;
      this.ruleForm.remark = remark;
      this.ruleForm.updateBy = updateBy;
      this.ruleForm.updateTime = updateTime;
      this.ruleForm.userId = userId;
      this.ruleForm.userName = userName;
      this.visible = true;
    },
    // 选择设备
    async OptionUpdate(row){
      // 先改id值
      this.userId=row.userId;
      // 再发送某id的请求，获取数据，赋给tableDataAdd 
      this.initAdd();
      this.visibleAdd = true;
    },
    // 根据当前页&每页展示条数，从服务器获取列表数据
    async initAdd(){
      this.tableLoadingAdd = true;
      try {
        let { pageNum, pageSize } = this.paginationAdd;
        let userId=this.userId;
        let { code, rows, total } = await this.$http.group.listByGroup(
          pageNum,
          pageSize,
          userId
        );
        if (code === 200) {
          // console.log(rows);
          this.paginationAdd.total = total;
          this.tableDataAdd = rows;
        } else {
          this.paginationAdd.total = 0;
          this.tableDataAdd = [];
        }
      } catch (_) {
        _;
      }
      this.tableLoadingAdd = false;
    },
    // 关闭选择设备
    closeDialogAdd(){
      this.visibleAdd = false;
      this.tableDataAdd=[];
      this.tableLoadingAdd =false,
      this.userId=1;
      this.paginationAdd={
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  created() {
    this.init();
  }
};
</script>

<style lang="less" scoped>
.group {
  width: 100%;
  margin: 10px;
  .handler-box {
    width: 100%;
    height: 73px;
    padding: 15px 20px 20px 20px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .leftWrap {
      width: 560px;
      height: 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      h1 {
        width: 68px;
        line-height: 36px;
        vertical-align: middle;
        font-size: 14px;
        color: #606266;
        font-weight: 700;
      }
      .el-input {
        width: 175px;
        margin-left: -15px;
        margin-top: 5px;
      }
      h2 {
        width: 68px;
        line-height: 36px;
        vertical-align: middle;
        font-size: 14px;
        color: #606266;
        font-weight: 700;
        margin-right: -20px;
      }
      .el-switch {
        margin-right: 20px;
      }
    }
  }
  &>.el-pagination {
  background-color: #fff;
  text-align: right;
  padding-top: 30px;
  padding-bottom: 80px;
}
}
.topWrap {
      width: 330px;
      height: 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      h1 {
        width: 68px;
        line-height: 36px;
        vertical-align: middle;
        font-size: 14px;
        color: #606266;
        font-weight: 700;
      }
      .el-input {
        width: 175px;
        margin-left: -15px;
      }
    }
.el-table {
  box-sizing: border-box;
  width: 100%;
  background-color: #fff;
  margin-top: 10px;
  padding: 15px 20px 20px 20px;
  box-sizing: border-box;
}
.el-input__inner,
.el-button {
  width: 73px;
  height: 28px;
  line-height: 1;
  padding: 7px 15px;
  border-radius: 3px !important;
}

.el-pagination {
  background-color: #fff;
  text-align: right;
  padding-top: 20px;
  padding-bottom: 0px;
}

</style>